package com.lyfei.yd.admin.web;

import com.lyfei.yd.admin.security.model.LoginBody;
import com.lyfei.yd.admin.security.model.LoginUser;
import com.lyfei.yd.admin.security.service.SysLoginService;
import com.lyfei.yd.admin.security.service.TokenService;
import com.lyfei.yd.admin.security.utils.SecurityUtils;
import com.lyfei.yd.common.constant.Constants;
import com.lyfei.yd.common.core.domain.AjaxResult;
import com.lyfei.yd.common.utils.ServletUtils;
import com.lyfei.yd.system.domain.entity.SysRole;
import com.lyfei.yd.system.domain.entity.SysUser;
import com.lyfei.yd.system.domain.vo.RouterVo;
import com.lyfei.yd.system.service.SysMenuService;
import com.lyfei.yd.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), false);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysRole role = sysUserRoleService.getRoleByUserId(loginUser.getUser().getId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("role", role);
        ajax.put("user", loginUser.getUser());

        return ajax;
    }

    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<RouterVo> menus = menuService.getMenuTreeByUser(sysUser);
        return AjaxResult.success(menus);
    }
}
